package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author 剑落萧瑟不自知
 * @Time 2024/4/10
 * @OverView 切面=切入点+通知（增强）
 */

@Aspect
@Slf4j
@Component
public class GuiguLoginAspect {


    @Autowired
    private RedisTemplate redisTemplate;


    //增强注解 @annotation
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiguLogin)")
    public Object authAround(ProceedingJoinPoint joinPoint,GuiguLogin guiguLogin) throws Throwable {
        //开启前置通知，将用户名获取到，放到当前线程中
        //1.根据上下路径获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //强转成ServletRequestAttributes 实现类
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        //获取到请求对象
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //2.获取请求对象中的token
        String token = request.getHeader("token");
        //3.判断token是否为空，不为空查询redis获取用户信息
        // 3.1 构建token对应的key，登陆成功后存入key形式：user:login:+token
        String loginKey =  RedisConstant.USER_LOGIN_KEY_PREFIX+token;
        //3.2 查询redis里面的用户信息
        UserInfoVo  userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);
        //3.3 如果用户信息为空 或者 目标方法是否要求必须登陆 抛出异常 状态码为 218 前端跳转登陆页面
        if (guiguLogin.required() && userInfoVo==null){
            throw  new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //4.将用户id存入ThreadLocal里面
        if (userInfoVo!=null){
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        Object retVal;
        try {
            //二 执行目标方法（凡是在方法上加@GuiGuLogin注解）
            retVal = joinPoint.proceed();

        } finally {
            //三 后置通知
            log.info("----------后置通知.....");
            //5.清理ThreadLocal中用户信息-避免内存泄漏
            AuthContextHolder.removeUserId();
        }
        return retVal;
    }
}
  